package com.taorenqi.business.fragment.login;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.taorenqi.business.R;
import com.taorenqi.business.activity.LoginActivity;
import com.taorenqi.business.app.MyApp;
import com.taorenqi.business.fragment.base.BaseBackFragment;
import com.taorenqi.business.utils.Encoder;
import com.taorenqi.business.utils.ToastUtil;
import com.taorenqi.business.widget.statusview.StatusUtils;
import com.taorenqi.business.widget.statusview.StatusView;
import com.taorenqi.business.widget.subscribers.PageDataSubscriberOnNext;
import com.taorenqi.business.widget.subscribers.ProgressSubscriber;
import com.taorenqi.business.widget.verifycode.Rotate;
import com.taorenqi.data.cache.ACache;
import com.taorenqi.data.cache.EnumKey;
import com.taorenqi.data.common.BasePageableResponse;
import com.taorenqi.data.entity.login.CodeDataEntity;
import com.taorenqi.data.entity.login.LoginEntity;
import com.taorenqi.data.requestmsgtoken.RegisterDataHttpRequest;
import com.taorenqi.data.service.LoginDataHttpRequest;
import com.taorenqi.data.utils.PhoneUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 企业用户
 * A simple {@link Fragment} subclass.
 */
public class RegisterCompanyFragment extends BaseBackFragment {


    @Bind(R.id.status_view)
    StatusView statusView;
    @Bind(R.id.toolbar_back)
    ImageView toolbarBack;
    @Bind(R.id.toolbar_title)
    TextView toolbarTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.et_register_company_phone)
    EditText etRegisterCompanyPhone;
    @Bind(R.id.et_register_company_pw)
    EditText etRegisterCompanyPw;
    @Bind(R.id.cb_register_company_isShow)
    CheckBox cbRegisterCompanyIsShow;
    @Bind(R.id.et_register_company_pw_again)
    EditText etRegisterCompanyPwAgain;
    @Bind(R.id.cb_register_company_isShow_again)
    CheckBox cbRegisterCompanyIsShowAgain;
    @Bind(R.id.et_register_company_tuxing)
    EditText etRegisterCompanyTuxing;
    @Bind(R.id.iv_register_company_yzm)
    ImageView ivRegisterCompanyYzm;
    @Bind(R.id.et_register_company_msg)
    EditText etRegisterCompanyMsg;
    @Bind(R.id.tv_register_company_msg)
    TextView tvRegisterCompanyMsg;
    @Bind(R.id.et_register_company_yaoqingma)
    EditText etRegisterCompanyYaoqingma;
    @Bind(R.id.cb_register_company_agree)
    CheckBox cbRegisterCompanyAgree;
    @Bind(R.id.tv_register_company_agreement)
    TextView tvRegisterCompanyAgreement;
    @Bind(R.id.tv_register_company_comfire)
    TextView tvRegisterCompanyComfire;
    @Bind(R.id.tv_register_company_domore)
    TextView tvRegisterCompanyDomore;
    @Bind(R.id.tv_register_company_login)
    TextView tvRegisterCompanyLogin;

    private PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>> subscriberReg;
    private BasePageableResponse<CodeDataEntity> data;
    private PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>> subscriberCode;
    private PageDataSubscriberOnNext<BasePageableResponse<LoginEntity>> subscriber;
    private BasePageableResponse<LoginEntity> registerEntity;
    private String token;//发送短信返回的token
    private int time = 60;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    if (time == 0) {
                        time = 60;
                        if (tvRegisterCompanyMsg != null) {
                            tvRegisterCompanyMsg.setClickable(true);
                            tvRegisterCompanyMsg.setText("获取验证码");
                        }
                    } else {
                        if (tvRegisterCompanyMsg != null) {
                            tvRegisterCompanyMsg.setText("重新获取(" + (--time) + ")");
                            handler.sendEmptyMessageDelayed(100, 1000);
                        }
                    }
                    break;
            }
        }
    };

    public static RegisterCompanyFragment newInstance() {
        // Required empty public constructor
        RegisterCompanyFragment fragment = new RegisterCompanyFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_register_company, container, false);
        ButterKnife.bind(this, view);
        initToolbar();
        initView();
        initRequest();
        initCheckBox();
        editListener();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void initToolbar() {
        toolbarTitle.setText("注册账号");
    }

    private void initRequest() {

        //是否注册
        subscriberReg = new PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>>() {
            @Override
            public void onNext(BasePageableResponse<CodeDataEntity> entity) {
                data = entity;
                ToastUtil.showToast(_mActivity, "手机号未注册");
            }
        };
        //验证码
        subscriberCode = new PageDataSubscriberOnNext<BasePageableResponse<CodeDataEntity>>() {

            @Override
            public void onNext(BasePageableResponse<CodeDataEntity> entity) {
                data = entity;
                ToastUtil.showToast(_mActivity, "验证码发送成功");
                token = data.getToken();
                ACache.get(_mActivity).put(EnumKey.User.MSG_TOKEN, token);
            }
        };

        //注册
        subscriber = new PageDataSubscriberOnNext<BasePageableResponse<LoginEntity>>() {
            @Override
            public void onNext(BasePageableResponse<LoginEntity> entity) {
                registerEntity = entity;
                ACache.get(_mActivity).put(EnumKey.User.USER_TOKEN, registerEntity.getToken());
                //接口请求成功后处理
                //完善资料
                start(CompleteCompanyInfoFragment.newInstance());
            }
        };
    }

    private void initView() {
        ivRegisterCompanyYzm.setImageBitmap(Rotate.getInstance().createBitmap());
    }

    private void editListener() {
        etRegisterCompanyPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() == 11) {
                    checkReg(editable.toString());//检查号码是否已经注册了
                }
            }

        });
    }

    //检测是否注册
    private void checkReg(String s) {
        HashMap map = new HashMap();
        map.put("mobile", s);
        String sign = Encoder.getSigns(map);
        LoginDataHttpRequest.getInstance(MyApp.getApp()).postCheckReg(
                new ProgressSubscriber(subscriberReg, _mActivity), s, sign);

    }

    private void initCheckBox() {
        cbRegisterCompanyIsShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (cbRegisterCompanyIsShow.isChecked()) {
                    // 设置EditText文本为可见的
                    etRegisterCompanyPw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    // 设置EditText文本为隐藏的
                    etRegisterCompanyPw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                etRegisterCompanyPw.postInvalidate();
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = etRegisterCompanyPw.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }

            }
        });

        cbRegisterCompanyIsShowAgain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (cbRegisterCompanyIsShowAgain.isChecked()) {
                    // 设置EditText文本为可见的
                    etRegisterCompanyPwAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    // 设置EditText文本为隐藏的
                    etRegisterCompanyPwAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                etRegisterCompanyPwAgain.postInvalidate();
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = etRegisterCompanyPwAgain.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }

            }
        });


    }

    @OnClick({R.id.toolbar_back, R.id.cb_register_company_isShow, R.id.cb_register_company_isShow_again, R.id.iv_register_company_yzm, R.id.tv_register_company_msg, R.id.cb_register_company_agree, R.id.tv_register_company_agreement, R.id.tv_register_company_comfire, R.id.tv_register_company_domore, R.id.tv_register_company_login})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.iv_register_company_yzm:
                ivRegisterCompanyYzm.setImageBitmap(Rotate.getInstance().createBitmap());
                break;
            case R.id.tv_register_company_msg://发送验证码
                sendMsgCode();
                break;
            case R.id.tv_register_company_agreement:
                break;
            case R.id.tv_register_company_domore://企业用户
                start(RegisterFragment.newInstance());
                break;
            case R.id.tv_register_company_comfire://注册
                register();
                break;
            case R.id.tv_register_company_login://登录页面
                Intent intent = new Intent();
                intent.setClass(_mActivity, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;

            case R.id.toolbar_back:
                pop();
                break;
            case R.id.cb_register_company_isShow:
                break;
            case R.id.cb_register_company_isShow_again:
                break;
        }

    }

    private void sendMsgCode() {
        String mobile = etRegisterCompanyPhone.getText().toString().trim();//手机号
        if (TextUtils.isEmpty(mobile) || mobile.length() < 11) {
            ToastUtil.showToast(_mActivity, "请输入正确手机号码");
        } else {
            //发送验证码请求
            int reg = 1;
            Map<String, String> map = new HashMap<>();
            map.put("mobile", mobile);
            map.put("reg", reg + "");
            String sign = Encoder.getSigns(map);

            LoginDataHttpRequest.getInstance(MyApp.getApp()).postSendSms(
                    new ProgressSubscriber(subscriberCode, _mActivity), mobile, reg, sign);
            tvRegisterCompanyMsg.setText("重新获取(" + time + ")");
            tvRegisterCompanyMsg.setClickable(false);
            handler.sendEmptyMessageDelayed(100, 1000);
        }
    }

    private void register() {
        String mobile = etRegisterCompanyPhone.getText().toString().trim();//手机号
        String password = etRegisterCompanyPw.getText().toString().trim();//第一次密码
        String password_again = etRegisterCompanyPwAgain.getText().toString().trim();//第二次密码
        String tuxing = etRegisterCompanyTuxing.getText().toString().trim();//图形验证码
        String vcode = etRegisterCompanyMsg.getText().toString().trim();//短信验证码
        String spreadCode = etRegisterCompanyYaoqingma.getText().toString().trim();//邀请码
        String device = PhoneUtils.getPhoneIMEI(_mActivity);//设备id
        int isqy = 1;//企业用户
        Map<String, String> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("pwd", password);
        map.put("vcode", vcode);
        map.put("spreadCode", spreadCode);
        map.put("device", device);
        map.put("isqy", isqy + "");
        String sign = Encoder.getSigns(map);

        if (!cbRegisterCompanyAgree.isChecked()) {//是否同意注册协议
            ToastUtil.showToast(_mActivity, "请勾选阅读并接受注册协议");
            return;
        }

        if (TextUtils.isEmpty(mobile) || mobile.length() < 11) {
            ToastUtil.showToast(_mActivity, "请输入正确手机号码");
            return;
        }

        if (TextUtils.isEmpty(password) || password.length() < 6) {
            ToastUtil.showToast(_mActivity, "请按要求输入密码");
            return;
        }

        if (TextUtils.isEmpty(password_again) || password.length() < 6) {
            ToastUtil.showToast(_mActivity, "请按要求输入密码");
            return;
        }

        if (!password.equals(password_again)) {
            ToastUtil.showToast(_mActivity, "两次密码不一致");
            return;
        }

        if (!Rotate.getInstance().getCode().toUpperCase().equals(tuxing.toUpperCase())) {
            ToastUtil.showToast(_mActivity, "图形验证码错误");
            return;
        }

        if (TextUtils.isEmpty(vcode)) {
            ToastUtil.showToast(_mActivity, "请按要求输入验证码");
            return;
        }

//
//        if (TextUtils.isEmpty(token)) {
//            ToastUtil.showToast(_mActivity,"请发送验证短信");
//            return;
//        }

        RegisterDataHttpRequest.getInstance(MyApp.getApp()).postRegister(new ProgressSubscriber(subscriber, _mActivity),
                mobile, password, vcode, spreadCode, device, sign, isqy);
    }
}
